import { useMemberStore } from '@/stores'

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// 添加拦截器
const httpInterceptor = {
  // 拦截前触发
  invoke(option:UniNamespace.RequestOptions) {
    if(!option.url.startsWith('http')){
      option.url = baseURL + option.url
    }
    // 设置超时时间
    option.timeout = 10000
    // 设置小程序请求头标识
    option.header = {
      ...option.header,
      'source-client': 'miniapp'
    }
    // 添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if(token){
      option.header.Authorization = token
    }
  }
}
uni.addInterceptor('request',httpInterceptor)
uni.addInterceptor('uploadFile',httpInterceptor)

// 定义接口返回类型
interface Data<T>{
  code:string,
  msg:string,
  result:T
}

// 请求函数
export const http = <T>(option:UniNamespace.RequestOptions) => {
  // 返回Promise对象
  return new Promise<Data<T>>((res,req)=>{
    uni.request({
      ...option,
      // 成功
      success(result) {
        if(result.statusCode  >= 200 && result.statusCode < 300){
          res(result.data as Data<T>)
        } else if(result.statusCode === 401) {
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({url:'/page.login/login'})
          req(result)
        } else {
          uni.showToast({
            icon:'none',
            title:(result.data as Data<T>).msg || '请求错误'
          })
          req(result)
        }
      },
      // 失败
      fail(err){
        uni.showToast({
          icon:'none',
          title:'请求失败'
        })
        req(err)
      }
    })
  })
}
